package cn.xuexiluxian.open.framework.security.handler;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson.JSON;
import cn.xuexiluxian.open.common.entity.LoginUser;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.framework.event.SystemLoginLogEvent;
import cn.xuexiluxian.open.framework.security.filter.JwtAuthenticationFilter;
import cn.xuexiluxian.open.framework.security.utils.JwtTokenUtil;
import cn.xuexiluxian.open.system.model.entity.SystemLoginLog;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private Ip2regionSearcher regionSearcher;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = JwtTokenUtil.getLoginUserFromToken(request.getHeader(JwtAuthenticationFilter.HEADER_STRING));
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String ip = ServletUtil.getClientIP(request);
        String address = regionSearcher.getAddress(ip);
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        SystemLoginLog sysLoginLog = new SystemLoginLog();
        sysLoginLog.setId(IdUtil.getSnowflakeNextIdStr());
        sysLoginLog.setUserName(loginUser.getUsername());
        sysLoginLog.setIpaddr(ip);
        sysLoginLog.setLoginLocation(address);
        sysLoginLog.setBrowser(browser);
        sysLoginLog.setOs(os);
        sysLoginLog.setMsg("退出登录");
        sysLoginLog.setLoginTime(new Date());
        SpringUtil.getApplicationContext().publishEvent(new SystemLoginLogEvent(sysLoginLog));
        cn.xuexiluxian.open.common.utils.ServletUtil.renderString(response, JSON.toJSONString(ResponseResult.ok()));
    }
}

